import requests, os, pathlib
from urllib.parse import urlparse

def download_file(url) -> str:
    local_filename = url.split('/')[-1]
    with requests.get(url, stream=True) as r:
        r.raise_for_status()
        with open(local_filename, 'wb') as f:
            for chunk in r.iter_content(chunk_size=8192):
                f.write(chunk)
    return local_filename

def get_moved_file(url) -> str:
    parsed_url = urlparse(url)
    final: str = parsed_url.hostname + parsed_url.path
    return f'downloads/{final}'

def move_file(url, local_filename) -> str:
    parsed_url = urlparse(url)
    final: str = parsed_url.hostname + parsed_url.path
    os.makedirs(f'downloads/{pathlib.Path(final).parent}', exist_ok=True)
    if os.path.exists(f'downloads/{final}'):
        os.remove(f'downloads/{final}')
    os.rename(local_filename, f'downloads/{final}')
    return final

def cached_download(url) -> str:
    old_local_filename = download_file(url)
    local_filename = move_file(url, old_local_filename)
    return local_filename
